import axios from "axios";
import React, { useContext, useReducer } from "react";

/*
    后代传参：
    1. 定义一个上下文对象
        const titleContext = React.createContext()
    2. 通过 Provider 配置 value 属性将值传递到后代组件
        <titleContext.Provider value={{
            title: '大标题',
            msg: '传家宝'
        }}>
    3. 通过 useContext 接收祖先组件传递过来的数据
        const value = useContext(titleContext)
*/


const titleContext = React.createContext()

function First(props){
    return <>

    <h1>First - 父组件 - {props.name}</h1>
    <hr />
    <Second title ={props.name}></Second>


    {/* 用 Consumer的 接收数据 */}

    <titleContext.Consumer> 
        {
           value =>{
                return <div>
                   <p> {value.msg} - {value.title}</p>
                </div>
           }
        }
    </titleContext.Consumer>
    </>
}

function Second(props){

    const value = useContext(titleContext)

    return <>
        <h1>Second - 子组件 - {props.title}</h1>
        <h3>{value.msg}</h3>
    </>
}

function App(){
  return<div>
    <h1>App - 祖先组件</h1>
    <hr />
    <titleContext.Provider value={{
        title: "标题",
        msg: "传家宝"
    }}>
        <First name = "张三"></First>
    </titleContext.Provider>
  </div>
}

export default App;